package com.powernode.model;

import com.powernode.constant.BusinessEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName Result
 * @Description 项目统一响应结果对象
 * @Date 2024/07/20 14:20
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("项目统一响应结果对象")
public class Result<T> implements Serializable {

    /**
     * 响应码
     */
    @ApiModelProperty("状态码")
    private Integer code = 200;

    /**
     * 响应信息
     */
    @ApiModelProperty("响应信息")
    private String msg = "ok";

    /**
     * 响应数据
     */
    @ApiModelProperty("响应数据")
    private T data;

    /**
     * 操作成功
     * @param data 响应数据
     * @return 结果
     * @param <T> 泛型
     */
    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setData(data);
        return result;
    }

    /**
     * 操作失败
     * @param businessEnum 状态码枚举
     * @return 结果
     * @param <T> 泛型
     */
    public static <T> Result<T> fail(BusinessEnum businessEnum) {
        Result<T> result = new Result<>();
        result.setCode(businessEnum.getCode());
        result.setMsg(businessEnum.getDesc());
        return result;
    }

    /**
     * 操作失败
     * @param code 状态码
     * @param msg 信息
     * @return 结果
     * @param <T> 泛型
     */
    public static <T> Result<T> fail(Integer code,String msg) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }

    /**
     * 处理用户的操作
     * @param flag 操作是否成功
     * @return 结果
     */
    public static Result<String> handle(Boolean flag) {
        if (flag) {
            return Result.success(null);
        }
        return Result.fail(BusinessEnum.OPERATION_FAIL);
    }
}
